package com.feng.service.impl;

import com.alibaba.excel.util.BooleanUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.Exception.SystemException;
import com.feng.constants.SystemConstants;
import com.feng.domain.ResponseResult;
import com.feng.domain.entity.Comment;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.entity.User;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.domain.vo.CommentVo;
import com.feng.domain.vo.PageVo;
import com.feng.mapper.CommentMapper;
import com.feng.mapper.UserMapper;
import com.feng.service.CommentService;
import com.feng.service.UserService;
import com.feng.util.BeanCopyUtils;
import com.feng.util.SecurityUtils;
import com.feng.util.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author makejava
 * @since 2022-10-11 12:50:27
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult commentList(String commentType,Long articleId, Integer pageNum, Integer pageSize) {
        //查询对应文章的根评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        //对articleId进行判断，只有当type为0才需要查询id
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getArticleId,articleId);
        //根评论 rootId为-1
        queryWrapper.eq(Comment::getRootId,-1);

        //评论类型
        queryWrapper.eq(Comment::getType,commentType);

        //分页查询
        Page<Comment> page = new Page(pageNum,pageSize);
        page(page,queryWrapper);

        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());
        User user = UserThreadLocal.get();
        //查询所有根评论对应的子评论集合，并且赋值给对应的属性
        for (CommentVo commentVo : commentVoList) {
            //查询对应的子评论

            Long id=commentVo.getId();
            String key="comment:liked:"+id.toString();
            if(ObjectUtils.isEmpty(user)){

                commentVo.setIsLike(false);

            }
            else{

                Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, user.getId().toString());
                commentVo.setIsLike(BooleanUtils.isTrue(isMember));
            }
            List<CommentVo> children = getChildren(commentVo.getId());
            //赋值
            commentVo.setChildren(children);
        }


        return ResponseResult.okResult(new PageVo(commentVoList,page.getTotal()));
    }

    @Override
    public ResponseResult addcomment(Comment comment) {
        //如果登录过，才能到达此接口，如果被篡改过，不会到达此接口
        // 之前认证的时候，已经将LoginUser信息放入SecurityContextHolder，所以userId可以再此获取
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        Long id = loginUser.getUser().getId();
//        comment.setCreateBy(id);
        if(!StringUtils.hasText(comment.getContent())){
            throw new SystemException(AppHttpCodeEnum.ContentNotNull);
        }
        save(comment);

        //但是考虑到注册等表都需要这些字段，所以使用MP公共字段进行填充
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult likeArticle(Long id) {
        //1.获取登录用户，判断是否已经点赞
        //获取登录用户的id
        User user = UserThreadLocal.get();
        if(ObjectUtils.isEmpty(user)){
            throw  new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }


        //key为该评论的id
        String key="comment:liked:"+id.toString();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, user.getId().toString());
        LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getId,id);
        Comment one = this.getOne(queryWrapper);
        if(BooleanUtils.isFalse(isMember)){
            //2.如果未点赞，可以点赞

            //3.数据库点赞+1
            LambdaUpdateWrapper<Comment> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Comment :: getId, id);
            updateWrapper.set(Comment :: getLiked,one.getLiked()+1);

            boolean isSuccess = this.update(updateWrapper);
            //4.保存到redis中的set集合
            if(isSuccess){
                stringRedisTemplate.opsForSet().add(key,user.getId().toString());
            }

        }else {
            //如果已点赞,取消点赞
            LambdaUpdateWrapper<Comment> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Comment :: getId, id);
            updateWrapper.set(Comment :: getLiked,one.getLiked()-1);

            boolean isSuccess = this.update(updateWrapper);
            //点赞数-1，把用户从redis中的set集合移除
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(key,user.getId().toString());
            }

        }

        return ResponseResult.okResult();
    }

    /**
     * 根据根评论的id查询所对应的子评论的集合
     * @param id 根评论的id
     * @return
     */
    private List<CommentVo> getChildren(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
        //查询条件，该评论的id等于根评论的id
        queryWrapper.eq(Comment::getRootId,id);
        queryWrapper.orderByDesc(Comment::getCreateTime);
        List<Comment> list = this.list(queryWrapper);
        for (Comment comment : list) {
            Long ids=comment.getId();
            String key="comment:liked:"+ids.toString();
            User user = UserThreadLocal.get();

            if(ObjectUtils.isEmpty(user)){
                comment.setIsLike(false);
            }
            else{
                Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, user.getId().toString());
                comment.setIsLike(BooleanUtils.isTrue(isMember));
            }
        }
        List<CommentVo> commentVos = toCommentVoList(list);
        return commentVos;
    }

    /**
     * 将Comment类转化为ComenntVo
     * @param list
     * @return
     */
    public List<CommentVo> toCommentVoList(List<Comment> list){
        List<CommentVo> commentVos = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        //遍历vo集合
        for (CommentVo commentVo : commentVos) {
            //通过creatyBy查询用户的昵称并赋值
            Long createBy = commentVo.getCreateBy();
            User byId = userService.getById(createBy);
            if(ObjectUtils.isEmpty(byId)){
                commentVo.setUsername("用户已注销");
            }

            commentVo.setUsername(byId.getNickName());
            commentVo.setAvatar(byId.getAvatar());
            //通过toCommentUserId查询用户的昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if(commentVo.getToCommentUserId()!=-1){
                String toCommentUserName = userService.getById(commentVo.getToCommentUserId()).getNickName();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVos;
    }
    }


